package de.dopichaj.labrador.util.io;

import java.io.IOException;
import java.math.BigInteger;

public final class BitOutputStream {

    private final ByteWriter output;
    private static final int MAX_BUFFERED_BITS = 8;
    private int bufferedBits;
    private int buffer;
    
    public BitOutputStream(final ByteWriter output) {
        this.output = output;
        this.bufferedBits = 0;
    }
    
    /**
     * Write the lower <code>bitCount</code> bits from <code>value</code>,
     * from least significant to most significant.
     * @throws IOException 
     */
    public void writeBits(long value, int bitCount) throws IOException {
        
        assert value < (1L << bitCount);
        assert value >= 0;
        
        int currentBitCount = bitCount;
        while (currentBitCount > 0) {
            
            // buffer the bits that fit in the buffer
            final int bitsToBuffer = Math.min(currentBitCount,
                MAX_BUFFERED_BITS - bufferedBits);
            final long bitsToAdd = value & ((1 << bitsToBuffer) - 1);
            buffer |= bitsToAdd << bufferedBits;
            value >>= bitsToBuffer;
            bufferedBits += bitsToBuffer;
            currentBitCount -= bitsToBuffer;
            
            // flush the buffer
            if (bufferedBits == MAX_BUFFERED_BITS) {
                flush();
            }
        }
    }

    /**
     * Write the lower <code>bitCount</code> bits from <code>value</code>,
     * from least significant to most significant.
     * @throws IOException 
     */
    public void writeBits(final BigInteger value, int bitCount) throws IOException {

        int currentBitCount = bitCount;
        BigInteger remainder = value;
        while (currentBitCount > 0) {
            
            // buffer the bits that fit in the buffer
            final int bitsToBuffer = Math.min(currentBitCount,
                MAX_BUFFERED_BITS - bufferedBits);
            final BigInteger mask = BigInteger.valueOf((1 << bitsToBuffer) - 1);
            final long bitsToAdd = remainder.and(mask).longValue();
            buffer |= bitsToAdd << bufferedBits;
            remainder = remainder.shiftRight(bitsToBuffer);
            bufferedBits += bitsToBuffer;
            currentBitCount -= bitsToBuffer;
            
            // flush the buffer
            if (bufferedBits == MAX_BUFFERED_BITS) {
                flush();
            }
        }
    }


    public void flush() throws IOException {
        if (bufferedBits > 0) {
            output.write(buffer);
        }
        output.flush();
        buffer = 0;
        bufferedBits = 0;
    }
    
    public void close() throws IOException {
        flush();
    }

    public void writeUnary(final int value) throws IOException {
        
        assert value > 0;
        for (int i = 1; i < value; i++) {
            writeBits(1, 1);
        }
        writeBits(0, 1);
    }

    public void writeGamma(final int value) throws IOException {
        
        assert value > 0 : "Value should be > 0, is " + value;
        
        // determine the floor of the binary logarithm
        int log = floorLog(value);
        
        // write the logarithm in unary
        writeUnary(log + 1);
        
        // write the remaining bits
        writeBits(value - (1 << log), log);
    }

    private int floorLog(final int value) {
        int log = 1;
        while ((value >> log) != 0) {
            log++;
        }
        log--;
        return log;
    }

    public void writeDelta(final int value) throws IOException {

        // determine the floor of the binary logarithm
        int log = floorLog(value);

        // write the logarithm in gamma
        writeGamma(log + 1);
        
        // write the remaining bits
        writeBits(value - (1 << log), log);
    }
    
    static final int BITS_PER_BLOCK = 7;
    static final int BLOCK_LIMIT = 1 << (BITS_PER_BLOCK);
    
    public void writeVariableLengthInt(final int value) throws IOException {
        
        assert value >= 0;
        int currentValue = value;
        do {
            writeBits(currentValue % BLOCK_LIMIT, BITS_PER_BLOCK);
            currentValue >>= BITS_PER_BLOCK;
            writeBits(currentValue > 0 ? 1 : 0, 1);
        } while (currentValue != 0);
    }
    
    public void writeBytes(final byte[] bytes) throws IOException {
        for (final byte b : bytes) {
            writeBits(b >= 0 ? b : b + 256, 8);
        }
    }

    public void writeString(final String testString) throws IOException {
        
        final byte[] bytes = testString.getBytes();
        writeGamma(bytes.length);
        writeBytes(bytes);
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/